package system

import (
	"encoding/json"
	"ltbz/cultural_tourism_api/controllers"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/models/system"
	"ltbz/cultural_tourism_api/utils"
	"time"

	systemServices "ltbz/cultural_tourism_api/services/system"
)

// 系统菜单管理
type SysMenuController struct {
	controllers.BaseAuthController
}

// @Tags 系统模块
// @Title 新增菜单
// @Description 新增菜单
// @Param	request	body system.SysMenuAddReq true "type json string"
// @Success 200
// @router /menu/add [post]
func (this *SysMenuController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	req := new(system.SysMenuAddReq)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	item := new(system.SysMenu)
	item.ParentId = req.ParentId
	item.Name = req.Name
	item.Sort = req.Sort
	item.Hidden = req.Hidden
	item.HiddenLayout = req.HiddenLayout
	item.Component = req.Component
	item.IconPath = req.IconPath
	item.MenuType = req.MenuType
	item.Path = req.Path
	item.PathName = req.PathName
	item.ButtonCode = req.ButtonCode
	//添加校验，如果是按钮类型，则父级菜单不允许为0
	if req.MenuType == 1 {
		if req.ParentId == 0 {
			br.Msg = "请设置按钮的父级菜单！"
			br.ErrMsg = "请设置按钮的父级菜单"
			return
		}
		if req.ButtonCode == "" {
			br.Msg = "请设置按钮标识！"
			br.ErrMsg = "请设置按钮标识"
			return
		}
	}
	if req.ParentId > 0 {
		parentInfo, tErr := item.GetMenuByMenuId(req.ParentId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				br.Msg = "上级菜单不存在！"
				br.ErrMsg = "上级菜单不存在"
				return
			}
			br.Msg = "查询上级菜单出错！"
			br.ErrMsg = "查询上级菜单出错,Err:" + tErr.Error()
			return
		}
		if parentInfo.RootId == 0 {
			item.RootId = parentInfo.MenuId
		} else {
			item.RootId = parentInfo.RootId
		}

		item.Level = parentInfo.Level + 1
		if item.Level >= 3 {
			br.Msg = "不允许设置四级菜单！"
			br.ErrMsg = "不允许设置四级菜单"
			return
		}
	}
	// 判断是否存在相同的菜单名称
	cond := " AND parent_id = ? AND name = ? AND menu_type=?"
	pars := make([]interface{}, 0)
	pars = append(pars, item.ParentId, item.Name, item.MenuType)
	exitList, err := item.GetMenuListByCondition(cond, pars, "")
	if err != nil {
		br.Msg = "查询菜单出错！"
		br.ErrMsg = "查询菜单出错"
		return
	}
	if len(exitList) > 0 {
		br.Msg = "该菜单名称已存在！"
		br.ErrMsg = "该菜单名称已存在"
		return
	}
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	err = item.Add()
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "保存成功"
	return
}

// @Tags 系统模块
// @Title 获取菜单列表
// @Description 获取菜单列表
// @Param	request	body system.SysAdminListReq true "type json string"
// @Success 200
// @router /menu/list [post]
func (this *SysMenuController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	//获取jwt数据失败
	sysUser := this.SysUser
	list, err, errMsg := systemServices.MenuList(sysUser)
	if err != nil {
		br.Msg = "获取失败！" + errMsg
		br.ErrMsg = "获取失败，Err:" + err.Error() + ";errMsg:" + errMsg
		return
	}

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = list
	return
}

// @Tags 系统模块
// @Title 获取全部菜单列表
// @Description 获取全部菜单列表
// @Param	request	body system.MenuListReq true "type json string"
// @Success 200
// @router /menu/all_list [post]
func (this *SysMenuController) AllList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	req := new(system.MenuListReq)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	count, list, err, _ := systemServices.AllMenuList(req, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	page := utils.GetPaging(req.CurrentIndex, req.PageSize, count)

	resp := new(system.SysMenuAllListPageResp)
	resp.Paging = page
	resp.List = list

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
}

// @Tags 系统模块
// @Title 获取按钮列表
// @Description 获取按钮列表
// @Param	request	body system.MenuShortListItem true "type json string"
// @Success 200
// @router /menu/buttons [post]
func (this *SysMenuController) ButtonList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	req := new(system.MenuShortListItem)
	body := this.Ctx.Input.RequestBody
	if string(body) != "" {
		err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	sysUser := this.SysUser
	if sysUser.RoleId <= 0 {
		br.Msg = "获取成功！"
		br.ErrMsg = "获取成功"
		return
	}

	list, err, errMsg := systemServices.ButtonList(sysUser.RoleId, req)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error() + ";errMsg:" + errMsg
		return
	}
	buttonList := make([]*system.SysMenuButtonResp, 0)
	for _, v := range list {
		tmp := new(system.SysMenuButtonResp)
		tmp.MenuId = v.MenuId
		tmp.ParentId = v.ParentId
		tmp.MenuType = v.MenuType
		tmp.Name = v.Name
		tmp.ButtonCode = v.ButtonCode
		buttonList = append(buttonList, tmp)
	}
	br.Ret = 200
	br.Msg = "获取成功"
	br.Data = buttonList
}

// @Tags 系统模块
// @Title 编辑菜单
// @Description 编辑菜单
// @Param	request	body system.SysMenuEditReq true "type json string"
// @Success 200
// @router /menu/edit [post]
func (this *SysMenuController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	req := new(system.SysMenuEditReq)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	menu := new(system.SysMenu)
	item, err := menu.GetMenuByMenuId(req.MenuId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该菜单不存在！"
			br.ErrMsg = "该菜单不存在，Err:" + err.Error()
			return
		}
		br.Msg = "查询菜单出错！"
		br.ErrMsg = "查询菜单出错，Err:" + err.Error()
		return
	}
	item.ParentId = req.ParentId
	item.Name = req.Name
	item.Sort = req.Sort
	item.Hidden = req.Hidden
	item.HiddenLayout = req.HiddenLayout
	item.Component = req.Component
	item.IconPath = req.IconPath
	item.MenuType = req.MenuType
	item.Path = req.Path
	item.PathName = req.PathName
	item.ButtonCode = req.ButtonCode

	//添加校验，如果是按钮类型，则父级菜单不允许为0
	if req.MenuType == 1 {
		if req.ParentId == 0 {
			br.Msg = "请设置按钮的父级菜单！"
			br.ErrMsg = "请设置按钮的父级菜单"
			return
		}
		if req.ButtonCode == "" {
			br.Msg = "请设置按钮标识！"
			br.ErrMsg = "请设置按钮标识"
			return
		}
	}
	if req.ParentId > 0 {
		parentInfo, tErr := item.GetMenuByMenuId(req.ParentId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				br.Msg = "上级菜单不存在！"
				br.ErrMsg = "上级菜单不存在"
				return
			}
			br.Msg = "查询上级菜单出错！"
			br.ErrMsg = "查询上级菜单出错"
			return
		}
		// 按钮只能挂在二级菜单下面
		/*if req.MenuType == 1 && parentInfo.ParentId == 0{
			resp.Fail("按钮只允许挂在二级菜单下面", c)
			return
		}*/
		if parentInfo.RootId == 0 {
			item.RootId = parentInfo.MenuId
		} else {
			item.RootId = parentInfo.RootId
		}
		item.Level = parentInfo.Level + 1
		if item.Level >= 3 {
			br.Msg = "不允许设置四级菜单！"
			br.ErrMsg = "不允许设置四级菜单"
			return
		}
	} else if req.ParentId == 0 {
		item.RootId = 0
		item.Level = 0
	}
	// 判断是否存在相同的菜单名称
	if req.Name != item.Name {
		cond := "parent_id = ? and name = ? and menu_type=?"
		pars := make([]interface{}, 0)
		pars = append(pars, item.ParentId, item.Name, item.MenuType)
		exitList, err := item.GetMenuListByCondition(cond, pars, "")
		if err != nil {
			br.Msg = "查询菜单出错！"
			br.ErrMsg = "查询菜单出错,Err:" + err.Error()
			return
		}
		if len(exitList) > 0 {
			br.Msg = "该菜单名称已存在！"
			br.ErrMsg = "该菜单名称已存在"
			return
		}
	}

	updateParams := make(map[string]interface{})
	updateParams["parent_id"] = req.ParentId
	updateParams["name"] = req.Name
	updateParams["sort"] = req.Sort
	updateParams["component"] = req.Component
	updateParams["icon_path"] = req.IconPath
	updateParams["menu_type"] = req.MenuType
	updateParams["path"] = req.Path
	updateParams["path_name"] = req.PathName
	updateParams["button_code"] = req.ButtonCode
	updateParams["root_id"] = item.RootId
	updateParams["level"] = item.Level
	updateParams["hidden"] = req.Hidden
	updateParams["hidden_layout"] = req.ParentId

	whereParam := make(map[string]interface{})
	whereParam["menu_id"] = req.MenuId

	err = item.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	return
}

// @Tags 系统模块
// @Title 删除菜单
// @Description 删除菜单
// @Param	request	body system.MenuShortListItem true "type json string"
// @Success 200
// @router /menu/delete [post]
func (this *SysMenuController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	req := new(system.MenuShortListItem)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.MenuId <= 0 {
		br.Msg = "请选择要删除的菜单！"
		return
	}
	err, errMsg := systemServices.DeleteMenu(req)
	if err != nil {
		br.ErrMsg = "删除失败,Err:" + err.Error() + ";errMsg:" + errMsg
		return
	}
	br.Msg = "删除成功"
	br.Ret = 200
	return
}
